package middleware

import (
	"net/http"
)

// CommonCorsMiddleware : with jwt on the verification, no jwt on the verification
type CommonCorsMiddleware struct {
}

func NewCommonCorsMiddleware() *CommonCorsMiddleware {
	return &CommonCorsMiddleware{}
}

func (m *CommonCorsMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type")
		w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
		w.Header().Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Language, Content-Type, Expires, Last-Modified, New-Token, New-Expires-At")
		w.Header().Set("Access-Control-Allow-Credentials", "true")

		method := r.Method
		if method == "OPTIONS" {
			w.WriteHeader(http.StatusNoContent)
			return
		}

		next(w, r)
	}
}
